import { ref } from "vue";
import { useRoute, onBeforeRouteUpdate } from "vue-router";
import { useCookies } from "@vueuse/integrations/useCookies";
import { router } from "@/router";

export function useTabList() {
  const cookie = useCookies();
  const route = useRoute();
  const activeTab = ref(route.path);

  const tabList = ref([
    {
      title: "后台首页",
      path: "/",
    },
  ]);

  //添加标签导航
  function addTab(tab) {
    //findIndex的回调来检查数组内的path和传入的path是否匹配---匹配到了:false表示已存在
    let noTab = tabList.value.findIndex((t) => t.path == tab.path) == -1;
    if (noTab) {
      tabList.value.push(tab);
    }

    cookie.set("tabList", tabList.value);
  }

  //初始化标签导航列表--刷新之后不丢失
  function initTabList() {
    let tbs = cookie.get("tabList");
    if (tbs) {
      tabList.value = tbs;
    }
  }
  initTabList();

  //监听--to:到达的路径；from:从哪里来--onBeforeRouteUpdate 捕获到路由变化
  onBeforeRouteUpdate((to, from) => {
    //点击之后处于激活状态
    activeTab.value = to.path;
    addTab({
      title: to.meta.title,
      path: to.path,
    });
  });

  //点击标签导航栏实现路由切换
  const changeTab = (t) => {
    activeTab.value = t;
    router.push(t);
  };

  //t代表要关闭的路由
  const removeTab = (t) => {
    //获取当前路由列表和激活的路由
    let tabs = tabList.value;
    let a = activeTab.value;
    //如果关闭的是当前激活的路由
    if (a == t) {
      //遍历路由列表，找到要关闭的路由位置
      tabs.forEach((tab, index) => {
        if (tab.path == t) {
          //计算关闭后应激活的下一个标签--优先选择右侧，没有就左侧
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            a = nextTab.path; //更新下一个路由的路径
          }
        }
      });
    }

    activeTab.value = a; //更新激活的路由，自动触发changeTab事件
    //从路由列表中移除目标路由
    tabList.value = tabList.value.filter((tab) => tab.path != t);
    cookie.set("tabList", tabList.value); //更新cookie。持久化存储
  };

  //过滤功能
  const handleClose = (c) => {
    if (c == "clearAll") {
      //切换回首页
      activeTab.value = "/";
      //过滤只剩下首页
      tabList.value = [
        {
          title: "后台首页",
          path: "/",
        },
      ];
    } else if (c == "clearOther") {
      //过滤只剩下首页和当前激活的路由
      tabList.value = tabList.value.filter(
        (tab) => tab.path == "/" || tab.path == activeTab.value
      );
    }
    cookie.set("tabList", tabList.value);
  };

  return {
    activeTab,
    tabList,
    changeTab,
    removeTab,
    handleClose
  }
}
